#include "stdafx.h"
#include "ST_DataBase.h"

ST_DataBase::ST_DataBase()
{
	m_SqliteDB = NULL;
}

ST_DataBase::~ST_DataBase()
{
}
//
//bool ST_DataBase::InitDataBase()
//{
//	//char *szSqlCreateUserInfo="CREATE TABLE t_userinfo(c_id INTEGER primary key autoincrement, c_username char not null, c_password char not null, c_privilege smallint not null);"; 
//	//bool bRet = Execute(szSqlCreateUserInfo);
//	//if(!bRet)
//	//	return false;
//	//char *szSqlCreateUserInfoIndex = "CREATE INDEX 'idx_userinfo_username' on 't_userinfo' ('c_username');";
//	//bRet = Execute(szSqlCreateUserInfo);
//	//if(!bRet)
//	//	return false;
//	return true;
//}

bool ST_DataBase::Open(const char *szFileName)
{
	if(m_SqliteDB != NULL)
		return false;

	int iRet = sqlite3_open(szFileName,&m_SqliteDB);

	if(iRet != SQLITE_OK)
		return false;

	return true;
}

void ST_DataBase::Close()
{
	if(NULL != m_SqliteDB)
	{
		sqlite3_close(m_SqliteDB);
	}
}

static int callback(void *pInstance, int argc, char **argv, char **azColName) 
{ 
	if(NULL == pInstance)
		return -1;

	ST_Sql* pSql = (ST_Sql*)pInstance;
	pSql->FetchResult(argc, argv, azColName);

	return 0; 
}

bool ST_DataBase::Execute(ST_Sql* pSql)
{
	if(NULL == m_SqliteDB || NULL == pSql)
		return false;

	char* szErrMsg = 0;

	m_iErrorCode = sqlite3_exec(m_SqliteDB,pSql->GetSQL(),callback,pSql,&szErrMsg); 
	if(SQLITE_OK == m_iErrorCode)
		return true;

	if(szErrMsg != NULL)
	{
		memset(m_szError,0,MAX_ERROR_LENGTH+1);
		strncpy_s(m_szError,szErrMsg,MAX_ERROR_LENGTH);
		sqlite3_free(szErrMsg);
	}
	return false;
}
//
__int64	ST_DataBase::GetLastRowID()
{
	return sqlite3_last_insert_rowid(m_SqliteDB);
}
//
int	ST_DataBase::GetErrorCode()
{
	return m_iErrorCode;
}

const char* ST_DataBase::GetErrorMsg() const
{
	return (char*)m_szError;
}